/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.components.table;

import java.util.List;
import java.util.logging.Level;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.balisunrise.application.Application;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.Event;
import org.balisunrise.common.Grid;
import org.balisunrise.common.GridColumn;
import org.balisunrise.common.listeners.GridColumnListener;

/**
 *
 * @author Glauco
 */
public class ColumnSelectionListenerImpl implements ListSelectionListener{

    private Grid grid;
    private JTable table;
    private List<GridColumnListener> listeners;
    private int oldSelection = 0;

    public ColumnSelectionListenerImpl(Grid grid) {
        this.grid = grid;
    }

    public JTable getTable() {
        return table;
    }

    public void setTable(JTable table) {
        if(this.table != null)
            this.table.getColumnModel().getSelectionModel()
                    .removeListSelectionListener(this);
        this.table = table;
        this.table.getColumnModel().getSelectionModel()
                .setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.table.getColumnModel().getSelectionModel()
                .addListSelectionListener(this);
    }

    public List<GridColumnListener> getListeners() {
        return listeners;
    }

    public void setListeners(List<GridColumnListener> listeners) {
        this.listeners = listeners;
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting())
            return;

        DefaultListSelectionModel dlsm =
            (DefaultListSelectionModel) e.getSource();

        int selectedIndex = dlsm.getMinSelectionIndex();
        int columns = table.getColumnModel().getColumnCount();
        int selectedRow = table.getSelectionModel().getMaxSelectionIndex();

        boolean lastEditable = true;
        boolean last = columns == selectedIndex + 1;
        if(!last)
            for (int i = selectedIndex + 1; i < columns; i++) {
                if (table.isCellEditable(selectedRow, i)){
                    lastEditable = false;
                    break;
                }
            }

        if(oldSelection < 0 || selectedIndex < 0)
            return ;

        // PEGA OS GRID COLUMNS
        GridColumn oldGC = grid.getGridModel().getColumns()[oldSelection];
        GridColumn newGC = grid.getGridModel().getColumns()[selectedIndex];

        // COLUMN SELECTED EVENT
        Event evt = null;
        try{
            evt = Application.get().getFactory()
                    .createColumnSelectedEvent(grid, oldGC, newGC);
        }catch(FactoryException ex){
            Application.get().getLogger().log(Level.SEVERE,
                    "ColumnSelectionListener não pode criar ColumnSelectedEvent"
                    , ex);
        }
        for (GridColumnListener l : listeners) {
            l.columnSelected(evt);
        }
        grid.getOwner().actionPerformed(evt);

        // LAST COLUMN SELECTED EVENT
        if (last){
            evt = null;
            try{
                evt = Application.get().getFactory()
                        .createLastColumnSelectedEvent(grid, oldGC, newGC);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                    "ColumnSelectionListener não pode criar LastColumnSelectedEvent"
                    , ex);
            }
            for (GridColumnListener l : listeners) {
                l.lastColumnSelected(evt);
            }
            grid.getOwner().actionPerformed(evt);
        }

        // LAST EDITABLE COLUMN SELECTED EVENT
        if(lastEditable){
            evt = null;
            try{
                evt = Application.get().getFactory()
                        .createLastEditableColumnSelectedEvent(
                        grid, oldGC, newGC);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                    "ColumnSelectionListener não pode criar LastEditableColumnSelectedEvent"
                    , ex);
            }
            for (GridColumnListener l : listeners) {
                l.lastEditableColumnSelected(evt);
            }
            grid.getOwner().actionPerformed(evt);
        }

        oldSelection = selectedIndex;
    }

}
